<template>
    <div>
        <el-card class='!border-none mb-4' shadow='never'>
            <el-form
                class='mb-[-16px]'
                :model='queryParams'
                inline
            >
                <el-form-item label='订单号' prop='order_no'>
                    <el-input class='w-[280px]' v-model='queryParams.order_no' clearable placeholder='请输入订单号' />
                </el-form-item>
                <!--        <el-form-item label="付款时间" prop="pay_time">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.pay_time" clearable placeholder="请输入付款时间"/>-->
                <!--        </el-form-item>-->
                <el-form-item label='订单状态' prop='status'>
                    <!--        1代付款2待出行3待评论4退款成功5订单取消6已完成7退款中-->
                    <!--          <el-input class="w-[280px]" v-model="queryParams.status" clearable-->
                    <!--                    placeholder="请输入订单状态1代付款2待出行3待评论4退款成功5订单取消6已完成7退款中"/>-->
                    <el-select style='width:180px;' v-model='queryParams.status' placeholder='请选择'>
                        <el-option v-for='(item,index) in statusOption' :key='index' :value='item.value'
                                   :label='item.label' />
                    </el-select>
                </el-form-item>
                <!--        <el-form-item label="出行时间" prop="start_time">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.start_time" clearable placeholder="请输入出行时间"/>-->
                <!--        </el-form-item>-->
                <el-form-item label='是否结算' prop='is_settled'>
                    <!--          <el-input class="w-[280px]" v-model="queryParams.is_settled" clearable-->
                    <!--                    placeholder="请输入订单是否结算0未结算1结算"/>-->
                    <el-select style='width:180px;' v-model='queryParams.is_settled' placeholder='请选择'>
                        <el-option v-for='(item,index) in settledOption' :key='index' :value='item.value'
                                   :label='item.label' />
                    </el-select>
                </el-form-item>
                <!--        <el-form-item label="用户ID" prop="user_id">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.user_id" clearable placeholder="请输入用户ID"/>-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="联系人姓名" prop="linkman_name">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.linkman_name" clearable placeholder="请输入联系人姓名"/>-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="联系人手机号" prop="linkman_tel">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.linkman_tel" clearable placeholder="请输入联系人手机号"/>-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="联系人留言" prop="linkman_remake">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.linkman_remake" clearable placeholder="请输入联系人留言"/>-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="线路ID" prop="line_id">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.line_id" clearable placeholder="请输入线路ID"/>-->
                <!--        </el-form-item>-->
                <!--        <el-form-item label="第三方平台流水号" prop="transaction_id">-->
                <!--          <el-input class="w-[280px]" v-model="queryParams.transaction_id" clearable-->
                <!--                    placeholder="请输入第三方平台流水号"/>-->
                <!--        </el-form-item>-->

                <el-form-item>
                    <el-space>
                        <export-data
                            class='ml-2.5'
                            :fetch-fun='apiOrderLists'
                            :params='exportParams'
                            :page-size='pager.size'
                        />
                        <el-button type='primary' @click='resetPage'>查询</el-button>
                        <el-button @click='resetParams'>重置</el-button>
                    </el-space>

                </el-form-item>
            </el-form>
        </el-card>
        <el-card class='!border-none' v-loading='pager.loading' shadow='never'>
            <el-button v-perms="['order/add']" type='primary' @click='handleAdd'>
                <template #icon>
                    <icon name='el-icon-Plus' />
                </template>
                新增
            </el-button>
            <el-button
                v-perms="['order/delete']"
                :disabled='!selectData.length'
                @click='handleDelete(selectData)'
            >
                删除
            </el-button>
            <div class='mt-4'>
                <el-table :data='tableData' @selection-change='handleSelectionChange'>
                    <el-table-column type='selection' width='55' />
                    <el-table-column label='订单号' prop='order_no' width='220'>
                        <template #default='{row}'>
                            <el-button type='primary' @click='detailHandle(row)' link>{{ row.order_no }}</el-button>
                        </template>
                    </el-table-column>
                    <el-table-column label='订单金额' prop='order_price' show-overflow-tooltip />
                    <el-table-column label='修改金额' prop='edit_price' />
                    <el-table-column label='总金额' prop='total_price' show-overflow-tooltip />
                    <!--          <el-table-column label="优惠券ID" prop="coupon_id" show-overflow-tooltip/>-->
                    <el-table-column label='优惠券抵扣金额' prop='coupon_money' show-overflow-tooltip />
                    <el-table-column label='支付方式' prop='pay_type' show-overflow-tooltip />
                    <el-table-column label='付款时间' prop='pay_time' width='160' />
                    <el-table-column label='订单状态' prop='status' width='100'>
                        <template #default='{row}'>
                            <el-tag :type='row.statusType'>{{ row.statusText }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label='出行时间' prop='start_time' width='180' />
                    <el-table-column label='是否结算' prop='is_settled'>
                        <template #default='{row}'>
                            <el-tag :type='row.settledType'>{{ row.settledText }}</el-tag>
                        </template>
                    </el-table-column>
                    <!--          <el-table-column label="订单是否评价0否1是" prop="is_comment" show-overflow-tooltip/>-->
                    <el-table-column label='用户ID' prop='user_id' show-overflow-tooltip />
                    <!--          <el-table-column label="取消订单备注" prop="cancel_remake" show-overflow-tooltip/>-->
                    <el-table-column label='退款金额' prop='refund_money' show-overflow-tooltip />
                    <!--          <el-table-column label="0删除1显示" prop="is_delete" show-overflow-tooltip/>-->
                    <!--          <el-table-column label="成年人数" prop="adult_num" show-overflow-tooltip/>
                              <el-table-column label="儿童人数" prop="child_num" show-overflow-tooltip/>
                              <el-table-column label="老人人数" prop="old_num" show-overflow-tooltip/>
                              <el-table-column label="房间数" prop="room_num" show-overflow-tooltip/>
                              <el-table-column label="联系人姓名" prop="linkman_name" show-overflow-tooltip/>
                              <el-table-column label="联系人手机号" prop="linkman_tel" show-overflow-tooltip/>
                              <el-table-column label="联系人留言" prop="linkman_remake" show-overflow-tooltip/>
                              <el-table-column label="线路ID" prop="-->line_id" show-overflow-tooltip/>
                    <!--          <el-table-column label="第三方平台流水号" prop="transaction_id" show-overflow-tooltip/>-->
                    <el-table-column label='退款备注' prop='refund_remake' show-overflow-tooltip />
                    <el-table-column label='操作' width='200' fixed='right'>
                        <template #default='{ row }'>
                            <el-space>
                                <el-button type='primary' size='small' @click='detailHandle(row)'>详情</el-button>
                                <el-button :disabled='row.status !== 1' type='danger' size='small' @click='changePrice(row)'>修改金额</el-button>
                            </el-space>
                            <!--              <el-button-->
                            <!--                  v-perms="['order/edit']"-->
                            <!--                  type="primary"-->
                            <!--                  link-->
                            <!--                  @click="handleEdit(row)"-->
                            <!--              >-->
                            <!--                编辑-->
                            <!--              </el-button>-->
                            <!--              <el-button-->
                            <!--                  v-perms="['order/delete']"-->
                            <!--                  type="danger"-->
                            <!--                  link-->
                            <!--                  @click="handleDelete(row.id)"-->
                            <!--              >-->
                            <!--                删除-->
                            <!--              </el-button>-->
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class='flex mt-4 justify-end'>
                <pagination v-model='pager' @change='getLists' />
            </div>
        </el-card>
        <edit-popup v-if='showEdit' ref='editRef' :dict-data='dictData' @success='getLists' @close='showEdit = false' />
        <detail-vue ref='detailRef' />
    </div>
</template>

<script lang='ts' setup name='orderLists'>
import { usePaging } from '@/hooks/usePaging'
import { useDictData } from '@/hooks/useDictOptions'
import { apiOrderLists, apiOrderDelete, apiDetail } from '@/api/order'
import { timeFormat } from '@/utils/util'
import feedback from '@/utils/feedback'
import EditPopup from './edit.vue'
import DetailVue from './detail.vue'
import { getUserList } from '@/api/consumer'
import { ElMessageBox } from 'element-plus'
import request from '@/utils/request'

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
// 是否显示编辑框
const showEdit = ref(false)
const detailRef = ref(null)

function changePrice(row: any) {
    const inputValue = (row.edit_price * 1) > 0 ? row.edit_price : row.total_price
    ElMessageBox.prompt('请输入修改金额', '提示', {
        confirmButtonText: '确认修改',
        cancelButtonText: '取消操作',
        inputErrorMessage: '请输入合法的金额!',
        inputType: 'number',
        inputValue,
        inputPattern: /(^[1-9](\d+)?(\.\d{1,2})?$)|(^0$)|(^\d\.\d{1,2}$)/
    })
        .then(async ({ value }) => {
            const resp = await request.post({
                url: '/Order/adminEditPrice',
                data: {
                    edit_price: value,
                    id: row.id
                }
            })
           await getLists()
        })
        .catch(() => [])
}


async function detailHandle(row: any) {
    detailRef.value?.initData(row.id)
    // console.log(row, 'row')
    // const resp = await apiDetail(row.id)
    // console.log(resp,'resp')
}

const settledOption = computed(() => [
    //0未结算1结算
    {
        label: '未结算',
        value: 0
    },
    {
        label: '已结算',
        value: 1
    }
])
const statusOption = computed(() => [
//订单状态1代付款2待出行3待评论4退款成功5订单取消6已完成7退款中
    {
        label: '待付款',
        value: 1
    },
    {
        label: '待出行',
        value: 2
    },
    {
        label: '待评论',
        value: 3
    },
    {
        label: '退款成功',
        value: 4
    },
    {
        label: '订单取消',
        value: 5
    },
    {
        label: '已完成',
        value: 6
    },
    {
        label: '退款中',
        value: 7
    }
])

const exportParams = reactive({
    keyword: '',
    channel: '',
    create_time_start: '',
    create_time_end: ''
})
// 查询条件
const queryParams = reactive({
    order_no: '',
    pay_time: '',
    status: '',
    start_time: '',
    is_settled: '',
    user_id: '',
    linkman_name: '',
    linkman_tel: '',
    linkman_remake: '',
    line_id: '',
    transaction_id: ''
})

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}

// 获取字典数据
const { dictData } = useDictData('')

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiOrderLists,
    params: queryParams
})
const STATUS_ENUM = {
    '1': {
        text: '待付款',
        type: ''
    },
    '2': {
        text: '待出行',
        type: ''
    },
    '3': {
        text: '待评价',
        type: ''
    },
    '4': {
        text: '退款成功',
        type: 'info'
    },
    '5': {
        text: '订单取消',
        type: 'danger'
    },
    '6': {
        text: '已完成',
        type: 'success'
    },
    '7': {
        text: '退款中',
        type: 'warning'
    }
}
const SETTLED_ENUM = {
    0: {
        text: '未结算',
        type: 'danger'
    },
    1: {
        text: '已结算',
        type: ''
    }
}

function patchZero(v: number) {
    return ('0' + v).slice(-2)
}

function patchPayTime(timestamp: number) {
    if (!timestamp) return  '无'
    const date = new Date(timestamp)
    const [year, month, day, hour, minute] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
    return `${year}-${patchZero(month)}-${patchZero(day)} ${patchZero(hour)}:${patchZero(minute)}`
}

const tableData = computed(() => {
    // 1代付款2待出行3待评论4退款成功5订单取消6已完成7退款中
    // 0未结算1结算 is_settled
    console.log(pager.lists, 'lists')
    return pager.lists.map(item => {
        item.status *= 1
        const { status, is_settled, pay_time } = item
        const targetStatus = STATUS_ENUM[status]
        item.statusText = targetStatus.text || ''
        item.statusType = targetStatus.type || ''
        const targetSettled = SETTLED_ENUM[is_settled]
        item.settledText = targetSettled.text || ''
        item.settledType = targetSettled.type || ''
        item.pay_time = patchPayTime(pay_time * 1000)
        return item
    })
})
// 添加
const handleAdd = async () => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('add')
}

// 编辑
const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.setFormData(data)
}
// 删除
const handleDelete = async (id: number | any[]) => {
    await feedback.confirm('确定要删除？')
    await apiOrderDelete({ id })
    getLists()
}
setTimeout(() => {
    getLists()
}, 0)
</script>

